const jwt = require('jsonwebtoken');
const { PRIVATE_KEY, EXPIRED } = require('../Config').token;
class Jwt {
    static generateToken(payload) {
        // console.log(payload, PRIVATE_KEY, EXPIRED);
        const token = jwt.sign(payload, PRIVATE_KEY, { expiresIn: EXPIRED });
        return token;
    }
    static verifyToken(token) {
        try {
            let tokenInfo = jwt.verify(token, PRIVATE_KEY, { algorithms: ['HS256'] })
            return tokenInfo;
        } catch (err) {
            return 'Error';
        }
    }
}
var ExcludeArray = [
    '/api/user/login',
    '/api/user/regist',
    '/api/admin/login',
];
async function tokenvalidate(ctx, next) {
    if (ctx.req.url.indexOf('/api') == 0 && !ExcludeArray.includes(ctx.req.url)) {
        const token = ctx.request.header.token;//从请求头的authorization属性中获取token
        if (token) {
            const tokenInfo = Jwt.verifyToken(token);
            if (tokenInfo === 'Error') {
                ctx.status = 403;
                ctx.body = {
                    code: 'Token Error',
                    message: 'token无效 或 token已过期, 请重新登录'
                }
            } else {
                ctx.userInfo = tokenInfo.userInfo;
                await next();
            }
        } else {
            ctx.status = 403;
            ctx.body = {
                code: 'Token Error',
                message: '未包含Token信息，请登录'
            }
        }
    } else {
        await next()
    };
}

module.exports = {
    Jwt,
    tokenvalidate
};